<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/10/19
     * Time: 下午5:13
     */

    namespace app\payment\logic;


    use app\common\utils\UtilEncryption;
    use app\payment\model\WalletModel;
    use app\store\model\OrderModel;
    use think\Db;

    class PayWallet extends PayBase
    {

        /**
         * 钱包或积分支付
         * @param int $pay_type 支付类型
         * @param string $pay_sn 支付订单号
         * @param int $total_fee 交易金额
         * @param int $pay_point
         * @return array
         */
        static public function send($pay_type, $pay_sn, $total_fee = 0, $pay_point = 0):array
        {
            try {
                Db::startTrans();

                $OrderModel = OrderModel::where(['pay_sn' => $pay_sn])->find();

                if (!$OrderModel) {
                    return ['code' => 500, 'msg' => '订单不存在！', 'data' => []];
                }
                if ($OrderModel->status == OrderModel::STATUS_YES_PAY) {
                    return ['code' => 500, 'msg' => '订单已支付！', 'data' => []];
                }
                $OrderModel->transaction_id = UtilEncryption::MakeSn();
                $OrderModel->status = OrderModel::STATUS_YES_PAY;
                $OrderModel->pay_type = $pay_type;
                $OrderModel->pay_amount = $total_fee;
                $OrderModel->point = $pay_point;

                $OrderModel->save();

                //获取用户钱包
                $WalletMoney = WalletModel::userwallet($OrderModel->buyer_id);

                //获取积分兑换比例
                $module_config = module_config('store');
                $module_config['pay_point_deduction_ratio'];


                if ($WalletMoney->money < $total_fee) {
                    Db::rollback();
                    return ['code' => 500, 'msg' => '钱包余额不足！', 'data' => []];
                }
                if ($WalletMoney->point < $pay_point) {
                    Db::rollback();
                    return ['code' => 500, 'msg' => '积分数量不足！', 'data' => []];
                }

                WalletModel::where(['member_id' => $OrderModel->buyer_id])->setDec('point', $pay_point);
                WalletModel::where(['member_id' => $OrderModel->buyer_id])->setDec('money', $total_fee);
                Db::commit();
                return ['code' => 200, 'msg' => '支付成功！', 'data' => []];

            } catch (\Exception $exception) {
                Db::rollback();
                return ['code' => 500, 'msg' => '支付失败！', 'data' => []];
            }
        }
    }